package com.breeze.blockchain.socket.handler.service;

import com.alibaba.fastjson2.JSON;
import com.breeze.blockchain.socket.handler.WebSocketCmd;
import com.breeze.blockchain.socket.handler.msg.OnlineCountMsg;
import com.breeze.components.socket.WebSocketHeartBeatChecker;
import com.breeze.components.socket.WebSocketManager;
import com.breeze.components.socket.vo.WebSocketResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author breeze
 */
@Slf4j
@Service
public class OnlineCountService {

  @Resource WebSocketManager webSocketManager;
  @Resource WebSocketHeartBeatChecker webSocketHeartBeatChecker;

  public void pushOnlineCount() {
    webSocketHeartBeatChecker.check(webSocketManager, 10000, 3);
    WebSocketResponse<OnlineCountMsg> msg =
        WebSocketResponse.ok(WebSocketCmd.ONLINE.getCmd(), new OnlineCountMsg(getOnlineCount()));
    webSocketManager.broadcast(JSON.toJSONString(msg));
  }

  public int getOnlineCount() {
    return webSocketManager.size();
  }
}
